package org.redmaple.core.template.controller.interceptor;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * SpringMVC 拦截器
 * 
 * @author Xiangyun
 *
 */
public class RedmapleInterceptor implements HandlerInterceptor {

	public static final String REQUEST_ATTRIBUTE_STARTTIME_NAME = "__requeststartTime";

	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 过滤器组
	 */
	private List<InterceptorFilter> interceptorFilter = new ArrayList<InterceptorFilter>();

	public List<InterceptorFilter> getInterceptorFilter() {
		return interceptorFilter;
	}

	public void setInterceptorFilter(List<InterceptorFilter> interceptorFilter) {
		this.interceptorFilter = interceptorFilter;
	}

	/**
	 * 在业务处理器处理请求之前被调用 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
	 * 
	 * 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链,
	 * 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion()
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute(REQUEST_ATTRIBUTE_STARTTIME_NAME, startTime);

		String sessionId = request.getSession().getId();
		String requestType = request.getHeader("X-Requested-With");
		String url = request.getRequestURL().toString();
		String uri = request.getRequestURI();
		
		logger.info("┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳┳");
		logger.info("##########################################################");
		logger.info("接收到SESSIONID为 " + sessionId + " 的请求");
		logger.info("requestType = " + requestType);
		logger.info("uri = " + uri);
		logger.info("url = " + url);

		// 日志记录参数
		logRequestParamters(request);
		
		logger.info("##########################################################");

		for (InterceptorFilter filter : interceptorFilter) {
			if (!filter.doFilter(request, response)) {
				return false;
			}
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	private void logRequestParamters(HttpServletRequest request) {
		Enumeration<String> paramNames = request.getParameterNames();
		Map<String, Object> paramMaps = new HashMap<String, Object>();
		String paramName = null;
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			paramMaps.put(paramName, request.getParameterValues(paramName));
		}
		logger.info("request paramters:" + paramMaps.toString());
	}

	/**
	 * 业务处理完成之后，视图生成之前执行此方法
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		long endTime = System.currentTimeMillis();
		long startTime = (Long) request
				.getAttribute(REQUEST_ATTRIBUTE_STARTTIME_NAME);
		request.removeAttribute(REQUEST_ATTRIBUTE_STARTTIME_NAME);
		long executeTime = endTime - startTime;
		logger.info("执行时间: " + executeTime + "ms");
		logger.info("┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻┻");
	}

	/**
	 * 在DispatcherServlet完全处理完请求后被调用
	 * 
	 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
